<?php
/**
 * Created by PhpStorm.
 * User: varcher
 * Date: 2017/8/21
 * Time: 下午10:01
 */

use yii\db\Connection;
use yii\db\Command;
use yii\db\Query;
use yii\di\Instance;

class HistoriographerDBBatch extends HistoriographerDB
{
    private $insertArray    =   array();
    private $flushInterval  =   0;

    public function __construct($inDb = "dbHeimdallLog")
    {
        parent::__construct($inDb);
        $this->flushInterval  =   __HISTORIOGRAPHER_DBBATCH_FLUSH_INTERVAL__;    //TODO:后续想办法改成随数据库的参数
    }

    public function record(AfterImage $afterImage)
    {
        array_push($this->insertArray, $this->buildArray($afterImage));
        if (sizeof($this->insertArray) >= $this->flushInterval) {
            $this->flush();
        }
    }

    protected function flush()
    {
        if(sizeof($this->insertArray) > 0)
        {
			Yii::info("DBBatch flushed.");
            try {
                $command = $this->db->createCommand()->batchInsert('afterimageLog',
                    ['aiNo', 'aiTime', 'aiName', 'aiGalaxyNo', 'aiUniverseNo', 'aiType', 'aiStatus', 'aiElapsedTime', 'aiReturnCode'],
                    $this->insertArray);
                $command->execute();
            } catch (Exception $exception) {
                Yii::error("DBBatch flush failed, reason={$exception->getMessage()}");
                Yii::error("Array Info is : ".json_encode($this->insertArray));
            }
            $this->insertArray  =   array();
        }
    }

    public function __destruct()
    {
        $this->flush();
    }
}